import React, { Component, PropTypes } from 'react'
import { Modal, Button, message } from 'antd'
import { messages } from "share/common";
import FileSaver from "file-saver";
import paymentService from 'containers/pay/pay-workbench/pay-workbench.service'
import ResizeTable from "components/resize-table";

class ErrorModal extends Component {
  state = {
    exportLoading: false,
    data: []
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.handleData(nextProps.data);
    }
  }

  handleData = data => {
    let temp = [];
    Object.keys(data.errorMsg).map(item => {
      temp.push({ error: data.errorMsg[item], index: item });
    });
    console.log(temp);
    this.setState({ data: temp })
  };

  handleCancel = () => {
    const { close } = this.props;
    close();
  };

  handleExport = () => {
    const { data, close } = this.props;
    let hide = message.loading(messages('components.key476'/*正在生成文件..*/));
    this.setState({ exportLoading: true });
    paymentService.exportErrInfo(data.transactionOid).then(res => {
      let b = new Blob([res.data], { type: "file" });
      let name = messages('components.key472'/*错误信息*/);
      FileSaver.saveAs(b, `${name}.xlsx`);
      hide();
      this.setState({ exportLoading: false }, () => {
        close();
      });
    }).catch(e => {
      hide();
      this.setState({ exportLoading: false });
      message.error(e.response.data.message);
    })
  };

  render() {
    const { visible } = this.props;
    const { exportLoading, data } = this.state;
    return (
      <Modal
        visible={visible}
        footer={[
          <Button type={'primary'} onClick={this.handleExport} loading={exportLoading}>{messages('pay.key231')/*导出错误信息*/}</Button>,
          <Button onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
        ]}
        title={messages('pay.key232')/*错误信息*/}
        onCancel={this.handleCancel}
      >
        <ResizeTable
          bordered
          dataSource={data}
          columns={[
            { title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 54 },
            { title: messages('pay.key232')/*错误信息*/, dataIndex: 'error' }
          ]}
        />
      </Modal>
    )
  }

  static propTypes = {
    visible: PropTypes.bool,
    data: PropTypes.object,
    close: PropTypes.func
  };

  static defaultProps = {
    data: {}
  }
}

export default ErrorModal;
